#!/usr/bin/python
import struct, sys
import os.path
import math

import vector

class AccelControl():

	def __init__(self):
		f1="/dev/input/event2"
		f2="/dev/input/event3"

		if not os.path.exists(f1):
			self.f1=None
			self.f2=None
			return 
		
		#int, int, short, short, int
		self.fmt = "iihhi"
		#open file in binary mode
		self.s1 = open(f1,"rb")
		self.s2 = open(f2,"rb")


	def read(self):
		_r1=self.read1()
		r2=self.read2()

		# rotate r1 45 degrees

		r1=vector.rotate((_r1[0],_r1[1]), math.pi/4)+(_r1[2],)

		# average
		return map(lambda x: (x[0]+x[1])/2, zip(r1,r2))

	def read1(self):
		return self._reada(self.s1)

	def read2(self):
		return self._reada(self.s2)

	
	def _reada(self, f=None):

		if not f:
			return 0,0,0
			

		x = False
		y = False
		z = False

		event = f.read(16)

		while event:
			(time1,time2, type, code, value) = struct.unpack(self.fmt,event)
			time = time1 + time2 / 1000000.0

			if type == 2:
				if code == 0:
					x = value
				if code == 1:
					y = value
				if code == 2:
					z = value
			if type == 0 and code == 0:
				# sum = int(math.sqrt(x*x + y*y + z*z))
				return x,y,z
			event = f.read(16)

	def close(self):
		self.in_file.close()


if __name__=='__main__':
	a=AccelControl()
	print "Accel test:"
	while True:
		sys.stdout.write("\r% 5d% 5d% 5d"%a.read())
